window.addEventListener("load", function () {
  var focus = document.querySelector(".focus");
  var ul = document.querySelector(".ul1");
  var ol = focus.children[1];
  var focusWidth = focus.offsetWidth;
  var index = 0;
  var timer = setInterval(function () {
    index++;
    var translatex = -index * focusWidth;
    ul.style.transition = "all .3s";
    ul.style.transform = "translateX(" + translatex + "px)";
  }, 2000);
  // 等我们过渡完成之后 再去判断 监听过渡完成的事件 transitionend
  ul.addEventListener("transitionend", function () {
    if (index >= 3) {
      index = 0;
      ul.style.transition = "none";
      var translatex = -index * focusWidth;
      ul.style.transform = "translateX(" + translatex + "px)";
    } else if (index < 0) {
      index = 2;
      ul.style.transition = "none";
      var translatex = -index * focusWidth;
      ul.style.transform = "translateX(" + translatex + "px)";
    }
    // 小圆点跟随
    // 把ol里面的li带有current类名的选出来去掉类名 remove
    ol.querySelector("li.current").classList.remove("current");
    // 让当前索引号 的li 加上 current  add
    ol.children[index].classList.add("current");
  });
  // 手指滑动
  // 触摸元素 touchstart  获取手指初始坐标
  var startX = 0;
  var moveX = 0;
  var flag = false;
  ul.addEventListener("touchstart", function (e) {
    startX = e.targetTouches[0].pageX;
    clearInterval(timer);
  });

  // 移动手指touchmove  计算手指的滑动距离  并且移动盒子
  ul.addEventListener("touchmove", function (e) {
    // 计算移动距离
    moveX = e.targetTouches[0].pageX - startX;
    // 移动盒子 盒子原来的位置 + 手指移动给的距离
    var translatex = -index * focusWidth + moveX;
    ul.style.transition = "none";
    ul.style.transform = "translateX(" + translatex + "px)";
    flag = true; // 如果用户移动过我们在判断
    e.preventDefault();
  });

  // 手指离开 根据移动距离去判断是回弹还是播放下一张
  ul.addEventListener("touchend", function (e) {
    if (flag) {
      // 如果移动距离大于50px 就播放上一张或下一张
      if (Math.abs(moveX) > 50) {
        // 是右滑就是播放上一张 moveX是正值
        if (moveX > 0) {
          index--;
        } else {
          // 是左滑就是播放下一张 moveX是负值
          index++;
        }
        var translatex = -index * focusWidth;
        ul.style.transition = "all 0.3s";
        ul.style.transform = "translateX(" + translatex + "px)";
      } else {
        // 移动小于50 回弹
        var translatex = -index * focusWidth;
        ul.style.transition = "all 0.3s";
        ul.style.transform = "translateX(" + translatex + "px)";
      }
      clearInterval(timer);
      timer = setInterval(function () {
        index++;
        var translatex = -index * focusWidth;
        ul.style.transition = "all .3s";
        ul.style.transform = "translateX(" + translatex + "px)";
      }, 2000);
    }
  });
});
